package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.FreezeDetailMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mongo.MovementApi;
import com.tanhua.dubbo.mongo.VideoApi;
import com.tanhua.model.admin.FreezeDetail;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ManageService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private VideoApi videoApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private FreezeDetailMapper freezeDetailMapper;

    //用户数据分页
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findAllPage(page, pagesize);
        return new PageResult(page, pagesize, Math.toIntExact(iPage.getTotal()), iPage.getRecords());
    }

    //查询单个用户
    public UserInfo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        //当缓存中有数据说明该用户是被冻结状态
        if(redisTemplate.hasKey(Constants.FREEZE_USER + id.toString())){
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    //查询指定用户发布的动态
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        PageResult movementByUserId = movementApi.findByUserId(uid, page, pagesize);
        UserInfo byId = userInfoApi.findById(uid);
        List<Movement> items = (List<Movement>) movementByUserId.getItems();
        if (CollUtil.isEmpty(items)) {
            throw new BusinessException("该用户没有发布动态");
        }
        List<MovementsVo> movementsVoList = items.stream().map(item ->
                MovementsVo.init(byId, item)
        ).collect(Collectors.toList());
        movementByUserId.setItems(movementsVoList);
        return movementByUserId;
    }

    //查询指定用户视频
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        PageResult videosByUserId = videoApi.findByUserId(uid, page, pagesize);
        UserInfo byId = userInfoApi.findById(uid);
        List<Video> items = (List<Video>) videosByUserId.getItems();
        if (CollUtil.isEmpty(items)) {
            throw new BusinessException("该用户没有发布视频");
        }
        List<VideoVo> collect = items.stream().map(item -> VideoVo.init(byId, item)).collect(Collectors.toList());
        videosByUserId.setItems(collect);
        return videosByUserId;
    }

    //用户冻结
    public Map freeze(Map map) {
        if(map.isEmpty()){
            throw  new BusinessException("传入的数据为空");
        }
        log.info("传入的map数据{}",map.toString());
        FreezeDetail freezeDetail=new FreezeDetail();
        freezeDetail.setUserId(Long.valueOf(map.get("userId").toString()));
        freezeDetail.setFreezingTime(Integer.parseInt(map.get("freezingTime").toString()));
        freezeDetail.setFreezingRange(Integer.parseInt(map.get("freezingRange").toString()));
        freezeDetail.setReasonsForFreezing(map.get("reasonsForFreezing").toString());
        freezeDetail.setFrozenRemarks(map.get("frozenRemarks").toString());
        freezeDetail.setCreated(new Date());
        log.info("冻结数据{}",freezeDetail.toString());
        if (ObjectUtil.isEmpty(freezeDetail)) {
            throw new BusinessException("请输入信息！");
        }
        freezeDetailMapper.insert(freezeDetail);
        int days = 0;
        if (freezeDetail.getFreezingTime() == 1) {
            days = 3;
        }
        if (freezeDetail.getFreezingTime() == 2) {
            days = 7;
        }
        if (freezeDetail.getFreezingTime() == 3) {
            days = -1;
        }
        String s = JSON.toJSONString(freezeDetail);
        redisTemplate.opsForValue().set(Constants.FREEZE_USER
                + freezeDetail.getUserId().toString(), s, days, TimeUnit.MINUTES);
        Map m = new HashMap();
        m.put("message","冻结成功");
        return m;
    }

    //用户解冻
    public Map userUnfreeze(Map map) {
        Long userId = Long.valueOf(map.get("userId").toString());
        String reasonsForThawing = (String) map.get("reasonsForThawing");
        String frozenRemarks = (String) map.get("frozenRemarks");
        LambdaQueryWrapper<FreezeDetail>lqw=new LambdaQueryWrapper<>();
        lqw.eq(FreezeDetail::getUserId,userId);
        lqw.orderByAsc(FreezeDetail::getCreated);
        FreezeDetail freezeDetail = freezeDetailMapper.selectList(lqw).get(0);
        freezeDetail.setReasonsForThawing(reasonsForThawing);
        freezeDetail.setFrozenRemarks(frozenRemarks);
        freezeDetailMapper.updateById(freezeDetail);
       //删除缓存中的数据
        redisTemplate.delete(Constants.FREEZE_USER+userId.toString());
        Map m = new HashMap();
        m.put("message","解冻成功");
        return m;
    }
}
